/**
 * Created by shanyun.gu on 2017/3/24.
 */
//<input id="account" data-rule="minLength:12;maxLength:20;required:true;" />
define(["jquery-validate", "jquery"], function (validate, $) {
    var convertStrToJson = function (str) {
        var strJson = "{\"" + str.replace(/'/g, "\"").replace(/:/g, "\":").replace(/;/g, ",\"") + "}";
        return $.parseJSON(strJson);
    }
    return function (jObject) {
        var dataRule = "data-rule";
        var dataRuleMsg = "data-rule-msg";
        var roleId = "name";
        var ruleJson = {};
        var msgJson = {};
        jObject.find("input,select,textarea").each(function () {
            var objectControl = $(this);
            var type = objectControl.attr("type");
            if (type === "submit" || type === "button") {
                return;
            }
            var expAttrStr = objectControl.attr(dataRule);
            var msgAttr = objectControl.attr(dataRuleMsg);
            var id = objectControl.attr(roleId);
            if (id && id.length > 0) {
                if (expAttrStr && $.trim(expAttrStr).length > 0) {
                    var expAttr = convertStrToJson(expAttrStr);
                    ruleJson[id] = expAttr;
                }
                if (msgAttr && $.trim(msgAttr).length > 0) {
                    msgJson[id] = msgAttr;
                }
            }
        });
        var validateRootJson = {};
        validateRootJson["onsubmit"] = false;
        validateRootJson["rules"] = ruleJson;
        validateRootJson["messages"] = msgJson;
        validateRootJson["errorElement"] = "em";
        validateRootJson["errorPlacement"] = function (error, element) {
            error.addClass("help-block");
            if (element.prop("type") === "checkbox") {
                error.insertAfter(element.parent("label"));
            } else {
                error.insertAfter(element);
            }
        };
        validateRootJson["highlight"] = function (element, errorClass, validClass) {
            $(element).parents(".form_com").addClass("has-error").removeClass("has-success");
        };
        validateRootJson["unhighlight"] = function (element, errorClass, validClass) {
            $(element).parents(".form_com").addClass("has-success").removeClass("has-error");
        };
        return jObject.validate(validateRootJson);
    }
});